import { getUserInfo } from '@/api/index'
import { distributorGet } from '@/api'
import moment from 'moment'
export default {
	state: {
		token: localStorage.getItem('token'),
		userInfo: null,
		total: {}
	},

	mutations: {
		SET_TOKEN(state, token) {
			state.token = token
			localStorage.setItem('token', token)
		},
		SET_USER_INFO(state, userInfo) {
			state.userInfo = userInfo
		},
		SET_TOTAL(state, total) {
			total.time = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
			state.total = total
		}
	},

	actions: {
		login({ commit, state, dispatch }, token, userInfo) {
			commit('SET_TOKEN', token)
			commit('SET_USER_INFO', userInfo)
		},
		async getUserInfo({ commit, state, dispatch }, userInfo) {
			await getUserInfo().then((res) => {
				commit('SET_USER_INFO', res.data)
				if (!res.data.name) {
					dispatch('showUserForm')
				}
			})
			await dispatch('getTotal')
		},
		async getTotal({ commit, state, dispatch }) {
			await distributorGet().then((res) => {
				commit('SET_TOTAL', res.data)
			})
		},

		logout({ commit }) {
			commit('SET_TOKEN', '')
			commit('SET_USER_INFO', null)
			location.reload()
		}
	}
}
